import { useLocation } from 'react-router-dom';
import { useSafeState, useMemoizedFn, useAsyncEffect } from 'ahooks';
import tokenCenter from '@/helpers/token';

export const useToken = () => {
  const { pathname } = useLocation();
  const [loading, setLoading] = useSafeState(true);
  const [token, setToken] = useSafeState<string>();

  const loadToken = useMemoizedFn(async () => {
    const token = await tokenCenter.getToken();
    setToken(token);
    setLoading(false);
  });

  useAsyncEffect(loadToken, [pathname]);

  return [token, loading] as [string, boolean];
}

